var mongoose = require('mongoose');
const Commit = require('../model/commit.model');
//增
exports.create = function(req, res, next) {
        const commit = new Commit(req.body);
        //实例化对象，req.body代表的是post的数据提交，并且参数从body中获取
        commit.save().then(data => {
            //数据保存，在保存以后将数据用json形式进行输出
            data.date = new Date();
            console.log(data + '156465');
            // data.commitNumber = 0;
            // console.log(data);
            res.json(data);
        })
    }
    //删
exports.remove = function(req, res, next) {
        const id = req.params.id;
        Commit.findByIdAndRemove(id, function(err, data) {
            res.json({ message: '删除成功' })
        })
    }
    //改 req.body,req.query,req.params(斜杠....)
exports.update = function(req, res, next) {
    //先查找一个id值
    const id = req.params.id;
    Commit.findByIdAndUpdate(id, { $set: req.body }, { new: false }).then(data => {
        res.json(data);
    })
}


//查
exports.list = function(req, res, next) {
    const page = req.body.page ? req.body.page : 1;
    var limit = req.body.limit ? req.body.limit : 10;
    var queryconditions = {};
    if (req.body.name && req.body.name.trim().length > 0) {
        name = req.body.name;
        queryconditions = {
            name: new RegExp(name, 'i')
        };
    };

    console.log(queryconditions);

    if (req.body.comid && req.body.comid.trim().length > 0) {
        comid = req.body.comid;
        //对象合并
        queryconditions = Object.assign(queryconditions, {
            comid: comid
        });
    };

    // if (req.body.title && req.body.title.trim().length > 0) {
    //     title = req.body.title;
    //     queryconditions = Object.assign(queryconditions, {
    //         title: new RegExp(title, 'i')
    //     });
    // };

    Commit.paginate(queryconditions, { page: page, limit: limit }, function(err, result) {
        result.rows = result.docs;
        delete result.docs;
        // console.log(result);
        res.json(result);
    })
}

//删除选中
exports.removes = function(req, res, next) {
    var ids = req.body.ids;

    ids = ids.split(',');
    console.log(ids);
    if (ids.length > 0) {
        Commit.remove({ _id: { $in: ids } }).then(data => {
            res.json({ message: '多条数据删除成功' });
        });
    }
}